// 对应 云文档 - 文件管理 下的接口实现
import {Request, Response} from 'express';
import {Handler} from '@srcTypes/route';
import {httpClient} from '@srcUtils/req';
import {resp} from '@srcUtils/resp';
import {User} from '@srcDb/model/user';
import {getToken, queryUserInfo} from '@srcDb/redis/auth';
import {lark} from '@/config';
import {HttpUtils} from '@/utils/utils';

const FormData = require('form-data');
const multiparty = require('multiparty');
const fs = require('fs');

export const getSuiteMeta = async (authToken: string, requestData: object) => {
    return await httpClient.post({
        url: lark.env.api.DOCS_OPEN_API.SUITE.SUITE_META,
        requireToken: true,
        token: authToken,
        data: requestData,
    });
};

export const getSuiteMetaReq: Handler = async (req: Request, res: Response) => {
    const {uuid} = req.body;
    if (typeof uuid !== 'string') {
        res.json(resp.setFail().setMsg('用户不存在！').collect());
        return;
    }
    const user: User | null = await queryUserInfo(uuid as string);
    if (user === null) {
        res.json(resp.setFail().setMsg('用户身份已过期，请重新验证用户身份').collect());
        return;
    }
    const suiteMeta = await getSuiteMeta(user.access_token, req.body.request_docs);
    console.log(suiteMeta);
};
// 该接口只作为转发器，接受二进制流并上传到飞书
export const suiteUploadFile: Handler = async (req: Request, res: Response) => {
    const {type} = req.query;
    let access_token: string;
    const parent_type = 'explorer';
    const form = new multiparty.Form();
    form.encoding = 'utf-8';
    form.parse(req, async (err, fields, files) => {
        try {
            const parent_node = fields['parent_node'][0];
            const uuid = fields['uuid'][0];
            if (type === 'user') {
                const user: User | null = await queryUserInfo(uuid as string);
                access_token = user.access_token;
            } else {
                // 应用身份
                const auth = req.headers.authorization;
                access_token = await getToken(auth, 'T');
            }
            const inputFiles = files.file;
            const file = inputFiles[0];
            const file_name = file.originalFilename;
            const size = file.size;
            const request_body = new FormData();
            request_body.append('file_name', file_name);
            request_body.append('size', size);
            request_body.append('parent_node', parent_node);
            request_body.append('parent_type', parent_type);
            request_body.append('file', fs.createReadStream(file.path));
            // 默认为异步
            const content = await httpClient.post({
                url: lark.env.api.DOCS_OPEN_API.DRIVE.FILES_V1_UPLOAD_ALL,
                requireToken: true,
                token: access_token,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                    ...request_body.getHeaders(),
                },
                data: request_body,
            }).catch((err: Error) => {
                console.log(err);
            });

            res.json(resp.setCode(content.data.code).setData(content.data.data).collect());
        } catch (err) {
            console.log(err);
            res.json(resp.setCode(500).setMsg('internal error').collect());
        }
    });
};

export const createFolder: Handler = async (req: Request, res: Response) => {
    const token = await HttpUtils.getTokenFromRequest(req);
    const {folderToken} = req.params;
    const {title} = req.body;
    const api_url = HttpUtils.handleParamsPath(lark.env.api.DOCS_OPEN_API.DRIVE.EXPLORER_V2_FOLDER, folderToken);
    const folderRes = await httpClient.post({
       url: api_url,
       requireToken: true,
        token: token,
        data: {
           title,
        },
    }).catch((err: Error) => {
        console.log(err);
        res.json(resp.setFail().collect());
    });
    console.log(folderRes);
    const data = (folderRes as any).data;
    res.json(resp.setCode(data.code).setMsg(data.msg).setData(data.data).collect());
};
